package cn.fl.flowauth.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.flowauth.condition.PrjFlowAuthCtrlQC;
import cn.fl.flowauth.constant.PrjFlowAuthCtrlConstant;
import cn.fl.flowauth.service.IPrjFlowAuthCtrlService;
import cn.fl.flowauth.vo.PrjFlowAuthCtrlVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.vo.SysUsrVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 项目流程权限控制 控制层
 */
@Controller
@RequestMapping("/flowauth/prjFlowAuthCtrl")
public class PrjFlowAuthCtrlController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PrjFlowAuthCtrlController.class);

    /**
     * PrjFlowAuthCtrl 服务层BEAN
     */
    @Autowired
    private IPrjFlowAuthCtrlService prjFlowAuthCtrlService;

    @Autowired
    private IPrjBscInfoService prjBscInfoService;

    @Autowired
    private ISysUsrApiService sysUsrApiService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("flowauth/prjFlowAuthCtrl/prjFlowAuthCtrlList");
		// 事业部
		List<KeyValueVO> orgList = this.prjFlowAuthCtrlService.searchBusinessOrgList();
		view.addObject("orgList", JSON.toJSONString(orgList));
		//控制内容
		List<KeyValueVO> ctrlContentList = this.prjFlowAuthCtrlService.getCtrlContent();
		view.addObject("ctrlContentList",JSON.toJSONString(ctrlContentList));
		//控制原因
		List<KeyValueVO> ctrlReasonList = this.prjFlowAuthCtrlService.getCtrlReason();
		view.addObject("ctrlReasonList",JSON.toJSONString(ctrlReasonList));
		//状态--是 否
		List<KeyValueVO> ynList = this.prjFlowAuthCtrlService.searchYNList();
		view.addObject("ynList",JSON.toJSONString(ynList));

		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "跳转到新增页面prjFlowAuthCtrlAdd", CurrentThreadContext.getCurrentUserName());
        ModelAndView view = new ModelAndView("flowauth/prjFlowAuthCtrl/prjFlowAuthCtrlAdd");
        String editFlag = request.getParameter("editFlag");//1-新增，2-修改，3-详情
        if (StringUtils.isEmpty(editFlag)) {
            view.addObject("editFlag", "1");
        } else {
            view.addObject("editFlag", editFlag);
        }
        //控制内容
        List<KeyValueVO> ctrlContentList = this.prjFlowAuthCtrlService.getCtrlContent();
        JSONArray ctrlContentJSON = JSONArray.fromObject(ctrlContentList.toArray());
        view.addObject("ctrlContentJSON", ctrlContentJSON);
        //控制原因
        List<KeyValueVO> ctrlReasonList = this.prjFlowAuthCtrlService.getCtrlReason();
        JSONArray ctrlReasonJSON = JSONArray.fromObject(ctrlReasonList.toArray());
        view.addObject("ctrlReasonJSON", ctrlReasonJSON);
        // 项目类型(根据被控制人所在事业部显示业务类型)
        List<KeyValueVO> projectTypeList = this.sysDictionaryApiService.getKvListAll(DictionaryConstant.CODE_PRJ_TYPE_CD,
                CurrentThreadContext.getCurrentSysCd(), PrjFlowAuthCtrlConstant.ORG_CD);
        JSONArray projectTypeJSON = JSONArray.fromObject(projectTypeList.toArray());
        view.addObject("projectTypeJSON", projectTypeJSON);
        view.addObject("currentUserName", CurrentThreadContext.getCurrentUserName());
        // 添加时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String crtTm = sdf.format(new Date());
        view.addObject("crtTm", crtTm);
        view.addObject("currOrg", PrjFlowAuthCtrlConstant.ORG_CD);
        return view;
    }

    /**
     * 到选择组织用户页面
     */
    @RequestMapping(value = "/toChooseUsr.do", method = { RequestMethod.GET})
    public ModelAndView toChooseUsrWinPageDialog(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = new ModelAndView("flowauth/prjFlowAuthCtrl/flowChooseUsrDialog");
        String isMore = request.getParameter("isMore");
        String users = request.getParameter("_users");

        ListPageVO<SysUsrVO> listPage = null;
        if (StringUtils.isNotEmpty(users)) {
            List<SysUsrVO> list = new ArrayList<>();
            List<HashMap> selectionMap = JSON.parseArray(users, HashMap.class);
            for (HashMap<Long,SysUsrVO> hashMap : selectionMap) {
                list.addAll(hashMap.values());
            }
            listPage = new ListPageVO<SysUsrVO>(list, list.size());
            view.addObject("sysUsrVOS",JSON.toJSONString(listPage));
        }
        view.addObject("isMore", isMore);
        BaseLogUtils.newLogger("转到选择组织用户页面. view:{}",JSONObject.toJSONString(view)).info();
        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        BaseLogUtils.newLogger("toModifyPage.Start.id:{},usrNm:{}", id, CurrentThreadContext.getCurrentUserName()).info();
        ModelAndView view = new ModelAndView("flowauth/prjFlowAuthCtrl/prjFlowAuthCtrlAdd");
        view.addObject("id", id);
        String editFlag = request.getParameter("editFlag");//1-新增，2-修改，3-详情
        if (StringUtils.isEmpty(editFlag)) {
            editFlag = "2";
        }
        if ("3".equals(editFlag)) {
            view.setViewName("flowauth/prjFlowAuthCtrl/prjFlowAuthCtrlDetail");
        }
        view.addObject("editFlag", editFlag);
        PrjFlowAuthCtrlVO prjFlowAuthCtrlVO = this.prjFlowAuthCtrlService.selectById(Long.valueOf(id));
        view.addObject("prjFlowAuthCtrlVO", prjFlowAuthCtrlVO);
        //控制内容
        List<KeyValueVO> ctrlContentList = this.prjFlowAuthCtrlService.getCtrlContent();
        JSONArray ctrlContentJSON = JSONArray.fromObject(ctrlContentList.toArray());
        view.addObject("ctrlContentJSON", ctrlContentJSON);
        //控制原因
        List<KeyValueVO> ctrlReasonList = this.prjFlowAuthCtrlService.getCtrlReason();
        JSONArray ctrlReasonJSON = JSONArray.fromObject(ctrlReasonList.toArray());
        view.addObject("ctrlReasonJSON", ctrlReasonJSON);
        if (prjFlowAuthCtrlVO != null) {
            //添加人
            view.addObject("currentUserName", prjFlowAuthCtrlVO.getCrtUsrNm());
            // 添加时间
            if (null != prjFlowAuthCtrlVO.getCrtTm()) {
                view.addObject("crtTm", DateUtils.formatDateToString(prjFlowAuthCtrlVO.getCrtTm(), DateUtils.YYYY_MM_DDHHMMSS));
            }
            if (null != prjFlowAuthCtrlVO.getCtrlStartDt()) {
                view.addObject("ctrlStartDtVO", DateUtils.formatDateToString(prjFlowAuthCtrlVO.getCtrlStartDt(), DateUtils.YYYY_MM_DDHHMMSS));
            }
            if (null != prjFlowAuthCtrlVO.getCtrlEndDt()) {
                view.addObject("ctrlEndDtVO", DateUtils.formatDateToString(prjFlowAuthCtrlVO.getCtrlEndDt(), DateUtils.YYYY_MM_DDHHMMSS));
            }
            String passiveCtrlRlNm = prjFlowAuthCtrlVO.getPassiveCtrlRlNm() == null ? "" : prjFlowAuthCtrlVO.getPassiveCtrlRlNm();
            String passiveCtrlUsrNm = prjFlowAuthCtrlVO.getPassiveCtrlUsrNm() == null ? "" : prjFlowAuthCtrlVO.getPassiveCtrlUsrNm();
            view.addObject("passiveCtrlUsrNm", passiveCtrlRlNm + passiveCtrlUsrNm);

            //被控制人组织架构代码
            String passiveCtrlOrgCd = prjFlowAuthCtrlVO.getPassiveCtrlOrgCd();
            view.addObject("currOrg", passiveCtrlOrgCd);
            //项目类型(根据被控制人所在事业部显示业务类型)
            List<KeyValueVO> projectTypeList = this.sysDictionaryApiService.getKvListAll(DictionaryConstant.CODE_PRJ_TYPE_CD,
                    CurrentThreadContext.getCurrentSysCd(), PrjFlowAuthCtrlConstant.ORG_CD);
            JSONArray projectTypeJSON = JSONArray.fromObject(projectTypeList.toArray());
            view.addObject("projectTypeJSON", projectTypeJSON);
        }
        BaseLogUtils.newLogger("toModifyPage.End.id:{},usrNm:{}", id, CurrentThreadContext.getCurrentUserName()).info();
        return view;
    }

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String passiveCtrlUsrNm = request.getParameter("passiveCtrlUsrNm");
		String passiveCtrlRlNm = request.getParameter("passiveCtrlRlNm");
		String buOrgCd = request.getParameter("buOrgCd");
		String cstUsrNm = request.getParameter("cstUsrNm");
		String crtTmMin = request.getParameter("crtTmMin");
		String crtTmMax = request.getParameter("crtTmMax");
		String ctrlContent = request.getParameter("ctrlContent");
		String ctrlReason = request.getParameter("ctrlReason");
		String isValid = request.getParameter("isValid");

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

        PrjFlowAuthCtrlQC qc = new PrjFlowAuthCtrlQC();
        if (StringUtils.isNotEmpty(passiveCtrlUsrNm)) {
            qc.setPassiveCtrlUsrNm(passiveCtrlUsrNm);
        }
        if (StringUtils.isNotEmpty(passiveCtrlRlNm)) {
            qc.setPassiveCtrlRlNm(passiveCtrlRlNm);
        }
        if (StringUtils.isNotEmpty(buOrgCd)) {
            qc.setPassiveCtrlOrgCd(buOrgCd);
        }
        if (StringUtils.isNotEmpty(cstUsrNm)) {
            qc.setCrtUsrNm(cstUsrNm);
        }
        if (StringUtils.isNotEmpty(crtTmMin)) {
            qc.setCrtTmMin(crtTmMin);
        }
        if (StringUtils.isNotEmpty(crtTmMax)) {
            qc.setCrtTmMax(crtTmMax);
        }
        if (StringUtils.isNotEmpty(ctrlContent)) {
            qc.setCtrlContent(ctrlContent);
        }
        if (StringUtils.isNotEmpty(ctrlReason)) {
            qc.setCtrlReason(ctrlReason);
        }
        if (StringUtils.isNotEmpty(isValid)) {
            qc.setIsValid(Integer.valueOf(isValid));
            //flowStartTm在这里只是作为判断，并无实际意义
            qc.setFlowStartTm(DateUtils.formatDateToString(new Date(),"yyyy-MM-dd HH:mm:ss"));
        }
		page.setCondition(qc);
		BaseLogUtils.newLogger("项目流程控制管理列表.request:" + JSONObject.toJSONString(page)).info();
		Pager pager = this.prjFlowAuthCtrlService.searchListPage(page);
        List<PrjFlowAuthCtrlVO> list = new ArrayList<>();
        if(pager!=null && CollectionUtils.isNotEmpty(pager.getResultList())){
            list = (List<PrjFlowAuthCtrlVO>) pager.getResultList();
        }
        ListPageVO<PrjFlowAuthCtrlVO> listPage = new ListPageVO<PrjFlowAuthCtrlVO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjFlowAuthCtrlService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			PrjFlowAuthCtrlVO vo = this.prjFlowAuthCtrlService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        List<PrjFlowAuthCtrlVO> prjFlowAuthCtrlVOList = null;
        try {
            //需禁用记录的id
            String ids = request.getParameter("ids");
            List<Long> idList = null;
            if (StringUtils.isNotEmpty(ids)) {
                idList = new ArrayList<Long>();
                JSONArray userIdsArray = JSONArray.fromObject(ids);
                for (Object object : userIdsArray) {
                    idList.add(Long.valueOf(object.toString()));
                }
            }
            //如果有，需要先禁用
            if (CollectionUtils.isNotEmpty(idList)) {
                for (Long aLong : idList) {
                    boolean b = prjFlowAuthCtrlService.modifyIsvalid(aLong, 0);
                    BaseLogUtils.newLogger("设置限制无效，userId:{},result:{}",JSONObject.toJSONString(idList),b).info();
                }
            }
            prjFlowAuthCtrlVOList = this.getRequestParamForAdd(request);
            if (CollectionUtils.isEmpty(prjFlowAuthCtrlVOList)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_ADD_FAIL);
                BaseLogUtils.info(logger, "add", "新增prjFlowAuthCtrl信息,参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }
            boolean addResult = this.prjFlowAuthCtrlService.batchAdd(prjFlowAuthCtrlVOList);
            BaseLogUtils.info(logger, "add", "新增数据.addResult=" + addResult + ",DATA:" + JSONObject.toJSONString(prjFlowAuthCtrlVOList), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(prjFlowAuthCtrlVOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(prjFlowAuthCtrlVOList) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }


    /**
     * 校验是否存在已生效记录
     */
    @RequestMapping(value = "/checkCtrl.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object checkCtrl(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        //被控制人
        String passiveCtrlIdStr = request.getParameter("passiveCtrlId");
        List<Long> passiveCtrlIdList = new ArrayList<>();
        String[] passiveCtrlIdArr = passiveCtrlIdStr.split(",");
        for (int i = 0; i < passiveCtrlIdArr.length; i++) {
            if (StringUtils.isNotEmpty(passiveCtrlIdArr[i])) {
                passiveCtrlIdList.add(Long.valueOf(passiveCtrlIdArr[i]));
            }
        }
        //组织架构
        String passiveCtrlOrgCdStr = request.getParameter("passiveCtrlOrgCd");
        List<String> passiveCtrlOrgCdList = new ArrayList<>();
        String[] passiveCtrlOrgCdArr = passiveCtrlOrgCdStr.split(",");
        for (int i = 0; i < passiveCtrlOrgCdArr.length; i++) {
            if (StringUtils.isNotEmpty(passiveCtrlOrgCdArr[i])) {
                passiveCtrlOrgCdList.add(passiveCtrlOrgCdArr[i]);
            }
        }
        //id
        String id = request.getParameter("id");
        if (StringUtils.isNotEmpty(id)) {
            PrjFlowAuthCtrlVO vo = prjFlowAuthCtrlService.selectById(Long.valueOf(id));
            passiveCtrlIdList.add(vo.getPassiveCtrlId());
            passiveCtrlOrgCdList.add(vo.getPassiveCtrlOrgCd());
        }
        BaseLogUtils.newLogger("校验是否存在已生效记录！ctrlIdList:{}", JSONObject.toJSONString(passiveCtrlIdList)).info();

        PrjFlowAuthCtrlQC qc = null;
        Map<Long,String> map = new HashMap<>();
        for (int i = 0; i < passiveCtrlIdList.size(); i++) {
            qc = new PrjFlowAuthCtrlQC();
            if (StringUtils.isNotEmpty(id)) {
                qc.setExcId(Long.valueOf(id));
            }
            qc.setPassiveCtrlId(passiveCtrlIdList.get(i));
            qc.setFlowStartTm(DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DDHHMMSS));
            qc.setPassiveCtrlOrgCd(passiveCtrlOrgCdList.get(i));
            qc.setIsValid(1);
            qc.setIsDel(0);
            List<PrjFlowAuthCtrlVO> prjFlowAuthCtrlVOS = prjFlowAuthCtrlService.searchList(qc);
            BaseLogUtils.newLogger("校验是否存在已生效记录！request:{},response:{}",
                    JSONObject.toJSONString(qc),JSONObject.toJSONString(prjFlowAuthCtrlVOS)).info();
            if (CollectionUtils.isNotEmpty(prjFlowAuthCtrlVOS)) {
                for (PrjFlowAuthCtrlVO prjFlowAuthCtrlVO : prjFlowAuthCtrlVOS) {
                    map.put(prjFlowAuthCtrlVO.getId(),prjFlowAuthCtrlVO.getPassiveCtrlRlNm());
                }
            }
        }
        if (CollectionUtils.isMapNotEmpty(map)) {
            result.setSuccess(BaseConstant.IS_YESNO_YES);
            result.setData(JSONObject.toJSONString(map));
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_SUCC);
        } else {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        PrjFlowAuthCtrlVO entity = new PrjFlowAuthCtrlVO();
        try {
            //需禁用记录的id
            String ids = request.getParameter("ids");
            List<Long> idList = null;
            if (StringUtils.isNotEmpty(ids)) {
                idList = new ArrayList<Long>();
                JSONArray userIdsArray = JSONArray.fromObject(ids);
                for (Object object : userIdsArray) {
                    idList.add(Long.valueOf(object.toString()));
                }
            }
            //如果有，需要先禁用
            if (CollectionUtils.isNotEmpty(idList)) {
                for (Long aLong : idList) {
                    boolean b = prjFlowAuthCtrlService.modifyIsvalid(aLong, 0);
                    BaseLogUtils.newLogger("设置限制无效，userId:{},result:{}",JSONObject.toJSONString(idList),b).info();
                }
            }
            entity = this.getRequestParamForModify(request);
            if (entity == null || entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modify", "修改prjFlowAuthCtrl信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }
            boolean success = this.prjFlowAuthCtrlService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.info(logger, "modify", "修改prjFlowAuthCtrl失败.id=" + entity.getId() + ",DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改prjFlowAuthCtrl成功.id=" + entity.getId() + ",DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改prjFlowAuthCtrl失败.id=" + entity.getId() + ",DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "modify", "修改prjFlowAuthCtrl失败.id=" + entity.getId() + ",DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modifySts.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifySts(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        String id = request.getParameter("id");
        String isValid = request.getParameter("isValid");
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(isValid)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "modifySts", "修改prjFlowAuthCtrl状态,主键参数为空！", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        try {
            boolean success = this.prjFlowAuthCtrlService.modifyIsvalid(Long.valueOf(id), Integer.valueOf(isValid));
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.info(logger, "modify", "修改prjFlowAuthCtrl状态失败.id=" + id + ",isValid:" + isValid, CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改prjFlowAuthCtrl状态成功.id=" + id + ",isValid:" + isValid, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改prjFlowAuthCtrl状态失败.id=" + id + ",isValid:" + isValid + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "modify", "修改prjFlowAuthCtrl状态失败.id=" + id + ",isValid:" + isValid + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数(新增)
     *
     * @param request 请求
     * @return
     */
    private List<PrjFlowAuthCtrlVO> getRequestParamForAdd(HttpServletRequest request) throws Exception {
        BaseLogUtils.info(logger, "getRequestParamForAdd", "新增prjFlowAuthCtrl获取请求参数开始", CurrentThreadContext.getCurrentUserName());
        List<PrjFlowAuthCtrlVO> list = new ArrayList<>();
        //所属机构
        String passiveCtrlOrgCdStr = request.getParameter("passiveCtrlOrgCd");
        //被控制人
        String passiveCtrlIdStr = request.getParameter("passiveCtrlId");
        //控制内容
        String ctrlContent = request.getParameter("ctrlContent");
        //控制项目类型
        String ctrlPrjTypCd = request.getParameter("ctrlPrjTypCd");
        //添加原因
        String ctrlReason = request.getParameter("ctrlReason");
        //控制时间
        String ctrlStartDt = request.getParameter("ctrlStartDt");
        //控制结束时间
        String ctrlEndDt = request.getParameter("ctrlEndDt");
        //备注
        String ctrlRem = request.getParameter("ctrlRem");
        //是否允许发送至录单员
        String isAllowSendToRecoder = request.getParameter("isAllowSendToRecoder");

        if (StringUtils.isEmpty(passiveCtrlOrgCdStr)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "所属机构不能为空.");
        }

        if (StringUtils.isEmpty(passiveCtrlIdStr)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "被控制人不能为空.");
        }

        if (StringUtils.isEmpty(ctrlContent)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制内容不能为空.");
        }
        if (StringUtils.isEmpty(ctrlPrjTypCd)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制项目类型不能为空.");
        }
        if (StringUtils.isEmpty(ctrlStartDt)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制时间不能为空.");
        }
        if (StringUtils.isEmpty(ctrlEndDt)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制结束时间不能为空.");
        }
        if (null != ctrlStartDt && null != ctrlEndDt) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime = simpleDateFormat.parse(ctrlStartDt);
            Date endTime = simpleDateFormat.parse(ctrlEndDt);
            if (startTime.after(endTime)) {
                throw new BaseException("开始时间不能大于结束时间");
            }
        }
        if (StringUtils.isEmpty(isAllowSendToRecoder)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "发送至录单员不能为空.");
        }
        List<Long> passiveCtrlIdList = new ArrayList<>();
        String[] passiveCtrlIdArr = passiveCtrlIdStr.split(",");
        for (int i = 0; i < passiveCtrlIdArr.length; i++) {
            if (StringUtils.isNotEmpty(passiveCtrlIdArr[i])) {
                passiveCtrlIdList.add(Long.valueOf(passiveCtrlIdArr[i]));
            }
        }
        List<String> passiveCtrlOrgCdList = new ArrayList<>();
        String[] passiveCtrlOrgCdArr = passiveCtrlOrgCdStr.split(",");
        for (int i = 0; i < passiveCtrlOrgCdArr.length; i++) {
            if (StringUtils.isNotEmpty(passiveCtrlOrgCdArr[i])) {
                passiveCtrlOrgCdList.add(passiveCtrlOrgCdArr[i]);
            }
        }
        PrjFlowAuthCtrlVO prjFlowAuthCtrlVO = null;
        if (CollectionUtils.isNotEmpty(passiveCtrlIdList) && CollectionUtils.isNotEmpty(passiveCtrlOrgCdList)) {
            for (int i = 0; i < passiveCtrlIdList.size(); i++) {
                SysUsrDTO sysUsrDTO = sysUsrApiService.selectSysUsrById(passiveCtrlIdList.get(i), "11000", "0000");
                BaseLogUtils.newLogger("查询用户信息，sysUsrDTO:{}",JSONObject.toJSONString(sysUsrDTO)).info();
                if (null != sysUsrDTO) {
                    prjFlowAuthCtrlVO = new PrjFlowAuthCtrlVO();
                    prjFlowAuthCtrlVO.setPassiveCtrlId(sysUsrDTO.getId());
                    prjFlowAuthCtrlVO.setPassiveCtrlUsrNm(sysUsrDTO.getUsrNm());
                    prjFlowAuthCtrlVO.setPassiveCtrlRlNm(sysUsrDTO.getRefRlNm());
                    prjFlowAuthCtrlVO.setPassiveCtrlOrgCd(passiveCtrlOrgCdList.get(i));
                    prjFlowAuthCtrlVO.setCtrlContent(ctrlContent);
                    prjFlowAuthCtrlVO.setCtrlPrjTypCd(ctrlPrjTypCd);
                    prjFlowAuthCtrlVO.setCtrlReason(ctrlReason);
                    if (StringUtils.isNotEmpty(ctrlStartDt)) {
                        prjFlowAuthCtrlVO.setCtrlStartDt(DateUtils.formatStringToDate(ctrlStartDt, DateUtils.YYYY_MM_DDHHMMSS));
                    }
                    if (StringUtils.isNotEmpty(ctrlEndDt)) {
                        prjFlowAuthCtrlVO.setCtrlEndDt(DateUtils.formatStringToDate(ctrlEndDt, DateUtils.YYYY_MM_DDHHMMSS));
                    }
                    prjFlowAuthCtrlVO.setCtrlRem(ctrlRem);
                    prjFlowAuthCtrlVO.setIsAllowSendToRecoder(isAllowSendToRecoder);
                    prjFlowAuthCtrlVO.setCrtTm(new Date());
                    prjFlowAuthCtrlVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                    prjFlowAuthCtrlVO.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());
                    //启用状态,新增时默认启用
                    prjFlowAuthCtrlVO.setIsValid(1);
                    prjFlowAuthCtrlVO.setIsDel(0);
                    list.add(prjFlowAuthCtrlVO);
                }
            }
        }
        BaseLogUtils.info(logger, "getRequestParamForAdd", "新增prjFlowAuthCtrl获取请求参数结束list:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
        return list;
    }

    /**
     * 获取请求参数(修改)
     *
     * @param request 请求
     * @return
     */
    private PrjFlowAuthCtrlVO getRequestParamForModify(HttpServletRequest request) throws Exception {
        String id = request.getParameter("id");
        BaseLogUtils.info(logger, "getRequestParamForModify", "修改prjFlowAuthCtrl获取请求参数开始 id:" + id, CurrentThreadContext.getCurrentUserName());
        //控制内容
        String ctrlContent = request.getParameter("ctrlContent");
        //控制项目类型
        String ctrlPrjTypCd = request.getParameter("ctrlPrjTypCd");
        //添加原因
        String ctrlReason = request.getParameter("ctrlReason");
        //控制时间
        String ctrlStartDt = request.getParameter("ctrlStartDt");
        //控制结束时间
        String ctrlEndDt = request.getParameter("ctrlEndDt");
        //备注
        String ctrlRem = request.getParameter("ctrlRem");
        //是否允许发送至录单员
        String isAllowSendToRecoder = request.getParameter("isAllowSendToRecoder");
        if (StringUtils.isEmpty(id)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "ID不能为空.");
        }
        if (StringUtils.isEmpty(ctrlContent)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制内容不能为空.");
        }
        if (StringUtils.isEmpty(ctrlPrjTypCd)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制项目类型不能为空.");
        }
        if (StringUtils.isEmpty(ctrlStartDt)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制时间不能为空.");
        }
        if (StringUtils.isEmpty(ctrlEndDt)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "控制结束时间不能为空.");
        }
        if (StringUtils.isEmpty(isAllowSendToRecoder)) {
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "发送至录单员不能为空.");
        }
        //校验开始时间和结束时间
        if (null != ctrlStartDt && null != ctrlEndDt) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime = simpleDateFormat.parse(ctrlStartDt);
            Date endTime = simpleDateFormat.parse(ctrlEndDt);
            if (startTime.after(endTime)) {
                throw new BaseException("开始时间不能大于结束时间");
            }
        }
        PrjFlowAuthCtrlVO prjFlowAuthCtrlVO = new PrjFlowAuthCtrlVO();
        prjFlowAuthCtrlVO.setId(Long.valueOf(id));
        prjFlowAuthCtrlVO.setCtrlContent(ctrlContent);
        prjFlowAuthCtrlVO.setCtrlPrjTypCd(ctrlPrjTypCd);
        prjFlowAuthCtrlVO.setCtrlReason(ctrlReason);
        if (StringUtils.isNotEmpty(ctrlStartDt)) {
            prjFlowAuthCtrlVO.setCtrlStartDt(DateUtils.formatStringToDate(ctrlStartDt, DateUtils.YYYY_MM_DDHHMMSS));
        }
        if (StringUtils.isNotEmpty(ctrlEndDt)) {
            prjFlowAuthCtrlVO.setCtrlEndDt(DateUtils.formatStringToDate(ctrlEndDt, DateUtils.YYYY_MM_DDHHMMSS));
        }
        prjFlowAuthCtrlVO.setCtrlRem(ctrlRem);
        prjFlowAuthCtrlVO.setIsAllowSendToRecoder(isAllowSendToRecoder);
        prjFlowAuthCtrlVO.setMdfTm(new Date());
        prjFlowAuthCtrlVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        prjFlowAuthCtrlVO.setMdfUsrNm(CurrentThreadContext.getCurrentUserName());
        BaseLogUtils.info(logger, "getRequestParamForModify", "修改prjFlowAuthCtrl获取请求参数结束 id:" + id + ",prjFlowAuthCtrlVO:" + JSONObject.toJSONString(prjFlowAuthCtrlVO), CurrentThreadContext.getCurrentUserName());
        return prjFlowAuthCtrlVO;
    }

    /**
     * 通过组织机构ID获取客户经理列表
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getCstMgrListByOrgId.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object getCstMgrListByOrgId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String orgCd = request.getParameter("orgCd");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,"获取成功");
        if (StringUtils.isEmpty(orgCd)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("请先选择组织机构！");
            return result;
        }
        try {
            List<SysUsrVO> actMgrList = this.prjBscInfoService.getCstMgrListByOrgId(orgCd);
            if (null == actMgrList) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在！");
            }
            //拼接用户名和真实姓名
            for (SysUsrVO sysUsrVO : actMgrList) {
                sysUsrVO.setRefRlNm(sysUsrVO.getRefRlNm() + sysUsrVO.getUsrNm());
            }
            result.setData(actMgrList);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            logger.error(ex.getMessage(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            logger.error("获取数据失败！", ex);
        }
        return result;
    }

    /**
     * 通过所属事业部获取项目类型
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPrjTypCdListByOrgId.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object getPrjTypCdListByOrgId(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String orgCd = request.getParameter("orgCd");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
        if (StringUtils.isEmpty(orgCd)) {
            orgCd = CurrentThreadContext.getCurrentBuOrgCd();
        }
        try {
            //获取事业部编码
            if (orgCd.length() > 8) {
                orgCd = orgCd.substring(0, 8);
            }
            List<KeyValueVO> prjTypCdList = this.sysDictionaryApiService.getKvListAll(DictionaryConstant.CODE_PRJ_TYPE_CD,
                    CurrentThreadContext.getCurrentSysCd(), orgCd);
            if (null == prjTypCdList) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在！");
            }
            result.setData(prjTypCdList);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            logger.error(ex.getMessage(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            logger.error("获取数据失败！", ex);
        }
        return result;
    }

    /**
     * 获取所有事业部组织机构信息
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/searchOrgTree.do", method = { RequestMethod.GET })
    @ResponseBody
    public Object searchOrgTree(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功");
        try {
            Long currentOrgId = CurrentThreadContext.getCurrentOrgId();
            JSONArray array = this.prjBscInfoService.searchParentAndCurrentAllsOrgTree(currentOrgId, PrjFlowAuthCtrlConstant.ORG_CD);
            if (null == array) {
                array = new JSONArray();
            }
            result.setData(array);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            logger.error(ex.getMessage(), ex);
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("获取数据失败！");
            logger.error("获取数据失败！", ex);
        }
        return result;
    }
}

